Ad
Email Validation Client Side
<form action="#" method="post" id="book-list">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" class="form-control">
</div>
<input type="submit" value="Add" class="btn btn-primary btn-block">
</form>
<script type="text/javascript">
function isEmail(email){
return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z](2,4))$/.test(email);
}
const form = document.querySelector('#book-list').addEventListener('submit',(e) =>{
e.preventDefault();
const inputEmail = document.querySelector('#email').value;
if(isEmail(inputEmail) === false ){
console.log('you lost');
document.querySelector('#email').focus();
return false;
}else{
console.log('you win');
return true
}
});
</script>
Playing around with this email validation, is there anything wrong with the code? even I filled the field with the proper email address like [email protected] it kept printing you lost result instead of printing the you win, is it because the form submit?
Ad
Answer
You can use input type='email'
if you want to allow html5 to do the validation for you, the submit wont fire if the field is not valid.
Otherwise you can change your regexp a bit to the below one
([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad