Validate email input field form element - reactjs

Possible to validate multiple emails seperated by commas with react-hook-form .
So I have a material-ui text field which is uses react-hook-form for the validation..
Initial the input field takes a single email and it's being validated by the react-hook-form.
currently I want the user to be able to enter multiple emails separated by commas and also validates each one of them.
Currently what I'm able to do is validate when the user clicks on submit but , I want to be able to validate when the user is typing the emails.
<TextField
onChange={(e) => {
validateRecipientEmail(e.target.value);
}}
name='recipientEmail'
placeholder='sender#email.com'
fullWidth
inputRef={register({
required: true,
})}
error={errors.recipientEmail && true}
/>
{errors.recipientEmail && (
<Typography variant='caption' className={Type.textError}>
Invalid email address
</Typography>
)}
I found a way to kind of achieve the desire goal by doing the validation with onChange event listener.
but after doing the validation and populating the error on the screen. the error disappear when the input field is not focus.
Below is my validation
const validateRecipientEmail = (value) => {
let currentEmails = value.split(',').filter((e) => e && e.trim());
let regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]+$/i;
for (let i = 0; i < currentEmails.length; i++) {
if (!regex.test(currentEmails[i].replace(/\s/g, ''))) {
setrecipientEmailErrorMessage(
`Enter valid Email(s) seperated by comma (,)`
);
setError('recipientEmail', {
type: 'manual',
});
}
}
if (currentEmails.length > 10) {
setrecipientEmailErrorMessage(`Emails should not be more than 10`);
setError('recipientEmail', {
type: 'manual',
});
}
};

so i found out you can pass a function to validate attribute which solves my problem
<TextField
name='recipientEmail'
placeholder='Eg. recipient#email.com'
inputRef={register({
required: true,
validate: {
validEmail: (value) => {
let currentEmails = value
.split(',')
.filter((e) => e && e.trim());
let regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]+$/i;
for (let i = 0; i < currentEmails.length; i++) {
if (!regex.test(currentEmails[i].replace(/\s/g, ''))) {
return false;
}
}
},
emailLength: (value) => {
let currentEmails = value
.split(',')
.filter((e) => e && e.trim());
if (currentEmails.length > 10) {
return false;
}
},
},
})}
error={errors.recipientEmail && true}
fullWidth
/>
"validEmail" validate the email and
"emailLength" validate the email length
Thank You

Related

how to make password mask in ant design

I have a task, I need to make a password mask for registration.
<Form.Item
name='password'
label='Password'
rules={[
{required: true, message: 'Please input your password!'},
{
validate: (_, value) => {
console.log(111)
if (/(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[0-9!*+%-<>#[]{}_#a-zA-Z]{6,}/g.test(value)) {
return Promise.resolve()
}
return Promise.reject('The password must contain at least 8 characters (Latin letters, numbers and at least one character: ! * + % - < > # [ ] { } _ #)')
}
}
]}
>
<Input.Password/>
</Form.Item>
i did validate, but it doesn't work, i looked at examples, and it seems like i did an analog, but why doesn't it work...
The actual property for supplying a custom validation function for a rule is validator.
Change
validate: (_, value) => {
to:
validator: (_, value) => {

How can i make an optional field?

I am making a Checkout form but i dont know how can i make it optional? I'm new with react js and i badly need help because i have defense some time next week and this is the only problem that i am encountering with the revisions that they have said.
Anyway here it is.
const objChecker = (e, id) => {
const hasEmpty = Object.values(orderInfo).some(x => x == '' );
console.log(Object.values(orderInfo), hasEmpty, id)
if(hasEmpty){
window.alert('Please input all fields')
return false
} else {
console.log(e, 'e')
setOrderInfo({ ...orderInfo, payment_id: id })
}
}
<div className='checkout_modal_payment_method_wrap'>
{paymentMethods.length > 0 && paymentMethods.map(method => (
<label htmlFor={`payment_method_${method.id}`} key={method.id} className='checkout_modal_payment_method_item'
style={{display: method.id === 1 && product.category_id === 2 && 'none'}}>
<input type='radio' id={`payment_method_${method.id}`} name='payment_id' value={method.id} onChange={(e) => objChecker(e, method.id)} required checked={payment_id === method.id}/>
<div>
{method.payment_name}
</div>
The only fields that i want to declare as optional is the ADDRESS LINE 2 and TYPE OF EVENT only. The rest will be required
This is the UI

react-hook-form Controller onBlur callback not triggering validation

Want to trim an input field when user onBlurs.
<Controller
...
onBlur={([e]) => {
const { value } = e.target;
const trimmedValue = value.trim();
console.log('trim here: ', value, value.length, trimmedValue.length);
if (trimmedValue === '') {
console.log('error!!!');
return trimmedValue;
}
return trimmedValue;
}} />
Rule:
rules={{
pattern: {
value: new RegExp(firstName.validationString, 'i'),
message: 'First name must be 2 - 100 characters with no numbers.',
},
required: firstName.mandatory && 'Must fill in first name',
}}
The function is triggered and reaching the if-statement. But is not triggering an error even though I have a rule set as required.
use this in your register or controller
validate: (value) => { return !!value.trim()}
Take a look here: https://github.com/react-hook-form/react-hook-form/issues/1650

How do I validate a checkout form in React?

I am trying to implement a checkout form in React. The form has 4 fields in all: Name, CC Number, CC expiration and CVV. I am using a library that validates each field on unfocus. The validation is triggered by the validationCallback method which takes 3 arguments: field, status, and message. I'd like to key off of the status for each input and only allow submit once each status === true. Here is my code.
constructor(props) {
super(props);
this.state = {
nameOnCard: '',
errorMessage: '',
showLoaderForPayment: '',
collectJs: null,
token: null,
isPaymentRequestCalled: false,
showErrorModal: false,
paymentErrorText: '',
disabled: true,
};
}
I have a disabled property in my state which I'm initially setting to true.
validationCallback: (field, status, message) => {
if (status) {
this.setState({ errorMessage: '' });
} else {
let fieldName = '';
switch (field) {
case 'ccnumber':
fieldName = 'Credit Card';
break;
case 'ccexp':
fieldName = 'Expire Date';
break;
case 'cvv':
fieldName = 'Security Code';
break;
default:
fieldName = 'A';
}
if (message === 'Field is empty') {
this.setState({ errorMessage: `${fieldName} ${message}` });
} else {
this.setState({ errorMessage: `${message}` });
}
}
},
In the above method, I'd like to set disabled to false if each of the field's status===true... Below is the button which I'm setting to be the value of this.state.disabled.
<button
className="continueBtn disabled"
disabled={this.state.disabled}
onClick={this.handleCardSubmit}
>
<span className="fa fa-lock" />
Pay $
{selectedPayment.amount}
</button>
I hope this is enough of the code to help with the issue. I can provide more of the file if need be.
From what i understand, you want to set the button to NOT DISABLED if all the fields are filled properly, i.e. all status are true.
What you can do is maintain a boolean array for each field and update the status in that array, i.e. initialize an array of length = no. of fields (in your case 3) and set all values as false. False depicts that the field hasn't been validated.
this.state = {
statusArray = [false, false, false] // For as many fields
}
Then in validationCallback, set the index as true or false for that field i.e. if the 2nd field status is returned true by your validation library, set statusArray as [false, true, false].
The form will only be validated if all 3 of the values become true. So you can iterate over the array and check if array has all 3 values as true. or you can use the logical AND operator which returns true only if all values are true(the approach which i use below).
For the button,
<button disabled={this.checkDisable()}>
checkDisable = () => {
let temp = this.state.statusArray;
let answer = true;
for(int i=0;i<temp.length;i++)
answer = answer && temp[i];
return answer; // Only returns true if all 3 values are true
}
I hope you get it now.
You need to check 2 things, has the form been touched and are there any errors. I don't know what library you are using but most likely it has a property touched in it, if not add an onFocus to each input field and a touched property in your state. You don't really need a disabled property in your state since its a computed value. Just check on every render if the form has been touched and if there are any errors.
state = {
...,
touched: false,
...
}
handleFocus = () => this.setState({touched: true})
render(){
const disabled = !!(this.state.touched && this.state.errorCode)
return(
...
<input onFocus={this.handleFocus} ... />
...
<button disabled={disabled}
)
}
EDIT:
state = {
...
validInputs: []
}
validationCallback: (field, status, message) => {
if (status) {
this.setState((state) => ({ errorMessage: '', validInputs: [... new Set([...state.validInputs, field])] }));
} else {
...
render(){
const disabled = this.state.length < inputs.length // the number of the input fields
return(
...
<button disabled={disabled} >
...
)

How to prevent a user pasting specific special characters (only allowed characters include (_ - .) in a form using jsx

I also want to limit the first character to just a number or a letter.
This is what I have so far to prevent the user from typing in special characters:
validate(event) {
const keycode = event.keyCode || event.which || event.type === 'paste';
const key = String.fromCharCode(keycode);
const pattern = new RegExp('^[a-zA-Z0-9\\_\\.\\-]$');
return pattern.test(key) ? key : event.preventDefault();
}
const validateMyField = (currentFieldValue, props) => {
if (currentFieldValue.match(/^[a-zA-Z0-9\\_\\.\\-]+$/)) {
return true;
}
return false;
};
const templateNameValidator = createValidator(
validateMyField,
'You are attempting to paste with characters that are not allowed. Please remove characters and try again. (special characters can only include "_","-",".")'
);
<Field
className="usaa-input"
component={Textarea}
label="Template Name"
name="name"
maxLength={128}
minRows={1}
placeholder="Enter Template Name..."
validate={composeValidators(required, templateNameValidator)}
onKeyPress={this.validate}
/>
It might be easier to use a controlled input. This is where we get and set the value to and from the state.
this.state = {inputValue: ""}
...
validateBeforeInput(e){
if(matches the chars we want){
this.setState({inputValue: e.target.value})
}
}
...
<input
value={this.state.inputValue}
onChange{validateBeforeInput} // where the magic happens
/>

Resources