This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 3 years ago.
I'm looking to do a more comprehensive email validation than the one I currently have. If you take a look at my code, I'm only checking for # symbol and ends in .com. Is there a more comprehensive validation check I can include into my current code configuration?
JS:
this.state = {
inputs: {
name: '',
email: '',
message: '',
},
errors: {
name: false,
email: false,
message: false,
},
};
handleOnChange = e => {
const { name, value } = e.target;
if (name === 'email') {
this.setState({
inputs: {
...this.state.inputs,
[name]: value,
},
errors: {
...this.state.errors,
email:
(value.includes('#') && value.slice(-4).includes('.com'))
? false
: true,
},
});
} else {
this.setState({
inputs: {
...this.state.inputs,
[name]: value,
},
errors: {
...this.state.errors,
[name]: false,
},
});
}
};
The best way to validate email is using regular expressions:
const emailRegEx = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
The above will match 99.99% of valid emails
Related
There is a credit card component. It asks the user to enter credit card information. However, I want to automatically put a slash between the day and month when the user enters the credit card expiration date. I searched the expiration date entry as "auto slash when 2 digits are entered" but I haven't been successful yet.
i can write; 0614
The format i want; 06/14
How can I solve it?
js
const [expDateValidationState, setExpDateValidationState] = useState({
error: false,
helperText: '',
});
const expDateOnChange = (event) => {
if (expDateValidator(event.target.value)) {
setExpDateValidationState({ error: false, helperText: '' });
setPaymentInfo({
...paymentInfo,
expDate: event.target.value === '' ? null : event.target.value,
});
} else {
setExpDateValidationState({
error: true,
helperText: 'Please enter your expire date.',
});
setPaymentInfo({
...paymentInfo,
expDate: null,
});
}
const handleExpDateChange = (event) => {
expDateOnChange(event);
handleInputChange(event);
};
validator
export const expDateValidator = (expDate) => {
const expDateRegex = /^(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})$/;
return expDateRegex.test(expDate);
};
html
<AS.TextField
placeholder="aa/YY"
inputProps={{ maxLength: 5 }}
onChange={handleExpDateChange}
error={expDateValidationState.error}
helperText={expDateValidationState.helperText}
name="expDate"
value={paymentInfo.expDate}
/>
Try this one
const expDateOnChange = (event) => {
if (expDateValidator(event.target.value)) {
setExpDateValidationState({ error: false, helperText: '' });
let value = event.target.value;
if (value.length===2) value += "/"
setPaymentInfo({
...paymentInfo,
expDate: event.target.value === '' ? null : value,
});
} else {
setExpDateValidationState({
error: true,
helperText: 'Please enter your expire date.',
});
setPaymentInfo({
...paymentInfo,
expDate: null,
});
}
When I change some data I usually put it in the state. If you also keep your data in the state, you can modify your handleExpDateChange to something like this:
const [expirationDate, setExpirationDate] = useState();
const handleExpDateChange = (event) => {
if (event.target?.value?.length === 2 && expirationDate.length < 3) {
setExpirationDate(event.target.value + '/')
} else {
setExpirationDate(event.target.value)
}
}
This can be simplified if you use ternary expression or in any other way but this is just very simple and the first thing that came to my mind.
Hope this will be helpful.
I'm using Typescript and have this, I'm trying to create Joi validation object.
Example input :
{
key: 'name',
validate: Joi.required().options({
language: {
any: {
required: 'is required'
},
string: {
min: 'must be at least 3 Characters'
},
},
}),
}
And a method :
getObjects(inputs: Array<Input>) {
const newObject = {};
inputs.forEach(input => {
newObject[input.key] = input.validate;
});
return newObject;
}
But when checking newObject, it's only keys, and validation is undefined.
I realise this has something to do with the loop because this works.
newObject[inputs[0].key] = inputs[0].validate;
newObject[inputs[1].key] = inputs[1].validate;
for example i have an object with validation rules
validationRules = {
planType: {
group: 'personalData',
required: true,
messages: {
required: 'Required Field'
}
},
name: {
group: 'personalData',
required: true,
pattern: /\w+\s+\w+/,
messages: {
required: 'Required Field',
pattern: 'Insert first and last names'
}
},
}
I need to validate a form wizard by steps so I need to make a function just to validate each step
function isStepValid() {
console.log(lastActiveNav);
const currentStep = lastActiveNav.getAttribute('data-pane');
var stepRules = validationRules.filter(currentStep); // wont work cause not an array
console.log(stepRules); // this is the value in the group property in the validationRules
for (let key in validationRules) {
}
}
I want to loop only through the properties with the value in the group property that match. Sadly i can only find an answer using an array with filter.
const currentStep = lastActiveNav.getAttribute('data-pane');
Object.keys(validationRules)
.map(key => validationRules[key])
.filter(validationRule => validationRule.group === currentStep)
.forEach(validationRule => { // forEach/map/reduce depending what you want to do
// Code here
})
I want to create a custom Joi type for populatedStrings by using .extend(..) to create a type based on joi.string() which:
Trims the string
Changes the value to undefined if the trimmed string === '' so the validated output won't contain the key at all
Overrides .required() so it acts on the trimmed string and creates errors using my own language. When .required() is set on my type it means that it requires a string which does not only contain white space or is empty
My attempt so far which is close:
const StandardJoi = require("joi");
const Joi = StandardJoi.extend(joi => ({
base: joi.string(),
name: "populatedString",
language: {
required: "needs to be a a string containing non whitespace characters"
},
pre(value, state, options) {
value = value.trim();
return value === "" ? undefined : value;
},
rules: [
{
name: "required",
validate(params, value, state, options) {
if (value === undefined) {
return this.createError(
"populatedString.required",
{ v: value },
state,
options
);
}
return value;
}
}
]
}));
Examples of it working
Joi.populatedString().validate(" x "); // $.value === 'x'
Joi.populatedString().validate(" "); // $.value === undefined
// $.error.details
//
// [ { message: '"value" needs to be a a string containing non whitespace characters',
// path: [],
// type: 'populatedString.required',
// context: { v: undefined, key: undefined, label: 'value' } } ]
Joi.populatedString()
.required()
.validate(" ");
// $.value
//
// { inObj1: 'o' }
Joi.object()
.keys({
inObj1: Joi.populatedString()
})
.validate({ inObj1: " o " });
But it does not fail (as it should) for
// { error: null, value: {}, then: [λ: then], catch: [λ: catch] }
Joi.object()
.keys({
inObj2: Joi.populatedString(),
inObj3: Joi.populatedString().required()
})
.validate({ inObj2: " " });
Even though inObj3 is .required() and not supplied it doesn't fail.
I managed to solve it:
const BaseJoi = require("joi");
const Joi = BaseJoi.extend(joi => ({
base: joi.string(),
name: "populatedString",
language: {
required: "needs to be a a string containing non whitespace characters"
},
pre(value, state, options) {
value = value.trim();
return value === "" ? undefined : value;
},
rules: [
{
name: "required",
setup(params) {
return this.options({ presence: "required" });
},
validate(params, value, state, options) {
if (value === undefined) {
return this.createError(
"populatedString.required",
{ v: value },
state,
options
);
}
return value;
}
}
]
}));
The fix was to add setup and let it set the option presence = required if required() was called.
Hi Im having troubles setting the state when I press a button 'Send' on one email input.
I'm trying it avoiding mutation as React docs recommends.
My state properties are this:
state = {
emailForm: {
email: {
elementType: 'email-invitation-input',
elementConfig: {
type: 'email',
placeholder: 'Enter an email..',
},
value: '',
valid: true,
required: true
}
},
requestStatus : false,
validationMessage : null,
formIsValid: false,
}
So I tried three ways to set empty value to my email input trough the state but no one worked :(
First try:
I used ES6 spread operator to change it value but it doesn't change the input value:
this.setState({
email: {
...this.state.emailForm.email,
value: '',
},
});
this.setState({
email: Object.assign({}, this.state.emailForm.email, {
value: '',
}),
});
Another try using immutability-helper package
import update from 'immutability-helper';
let newData = { email: {
...this.state.emailForm.email,
value: '',
}, };
this.setState({
email: update(this.state.newData, {
value: {$set: newData},
})
});
Second try:
I used Ramda.js but it neither works.
setObjectByPath(fieldPath, value) {
this.setState({
emailForm: R.set(R.lensPath(fieldPath), value, this.state.emailForm)
})
}
setObjectByPath(this.state.emailForm.email,'');
Third try:
I used react-addons-update:
import update from 'react-addons-update';
this.setState({
email: update(this.state.newData, {
value: {$set: newData},
})
});
All tries does nothing or it creates a new email input with empty value below.
Thanks beforehand
this.setState(prevState => ({
emailForm: {
email: {
...prevState.emailForm.email,
value: ''
}
}
}));