This question already has answers here:
Strip white spaces on input
(4 answers)
Closed 6 years ago.
I have a signup form that requires an email. when a user uses an android device and enters their email, if they have used the device before android auto suggests their email. If the user selects the auto suggestion it ads a trailing blank space at the end. then when the user goes to signup the system says invalid email because of the blank space. users dont always see the blank space. How can I remove the trailing blank space automatically.
I already have a piece of js that uses the check this function to compare email address entered for repeat email.
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail');
var emailRepeat = document.getElementById('eMail_repeat');
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
var email = document.getElementById("eMail").value.trim();
var repeat = document.getElementById("eMail_repeat").value.trim();
demo can be found here. Enter whitespace after the email inputs to check.
edit: Clearer demo can be found here, with sample addresses provided, and highlighting the differences between using .trim() and not using it.
you can use $.trim() function here:
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail').value.trim();
var emailRepeat = document.getElementById('eMail_repeat').value.trim();
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
You can use Javascript's String.replace with this regex /\s+$/. It would replace the text with empty string.
string.replace(/\s+$/, '')
Example:
var testString = " test string ";
console.log(testString.replace(/\s+$/, ''); // logs: " test string"
DEMO
Note: We could have used the trim() function directly but it removes leading as well as trailing spaces whereas we want only trailing. trimLeft and trimRight are neither standerdized nor implemented in all browsers.
Just use the Jquery snippet below so that, even if you select an email with spaces, it will be trimmed using the input bind event.
It even will not allow spaces.
$(function(){
$('#eMail').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
$('#eMail_repeat').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="email" id="eMail"/>
<input type="email" id="eMail_repeat"/>
Pls run the code snippet, paste any email with spaces directly, and it automatically trim's the spaces.
Here is a fiddle
Related
thanks in advance for answering the question.
The goal in my form (as with many similar forms) is to check that
text field is not empty
password meets the criteria (to be honest, right now I would be happy with just anything in it)
email has text before "#", the "#" and text after "#".
depending on whether all checks are okay, to display an alert with the message.
bootstrap:
<form>
<div class="form-group">
<label for="exampleTextarea">Course/Lecturer feedback</label>
<textarea class="form-control" id="textArea" rows="3" placeholder="Please enter your feedback in this field. Your opinion matters and helps us to provide you with better serivce."></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Please enter your email address</label>
<input type="email" class="form-control" id="emailAddress" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Please enter your password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" onclick="submitData()">Submit</button>
</form>
javascript
//comment validation function
function textFieldValidate(textField){
var txtln = "";
if (txtln !=="")
return pattern.test(textField);
}
//email validation function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
//password validation function
// at least one number, one lowercase and one uppercase letter
// at least six characters
function passwordValidate(password){
var pw = new RegExp (/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/);
return pw.test(password);
}
function submitData(){
//retrieve the values
if(textFieldValidate(textField) && isValidEmailAddress(emailAddress) && passwordValidate(password)){
//send post request
alert("Thank you for your feedback! We have sent this to KGB and you should expect a call any moment now...");
}else{
//display error message
alert("Unfortunately information that you have entered was incorrect, please check the info and and resubmit");
return;
}
}
what I get at the moment is that my page refreshes and nothing happens.
Alright, it looks like the issue was with the id in html which was called textArea and in function I called it textField.
Now... the other problem is that it doesn't really validate anything. Just the pop up appears...
I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
A form that insert data into mysql but before inserting data I wanted to write a JavaScript that will validate the form before submit but can let it work. In the HTML I have added required and pattern attribute for the input to validate the form data and to check whether user fill the required fields but i also want to add a script that will also validate the form and show the a message in the tag with id errorMessage but it doesn't seem to work.
var inputFields = document.theForm.getElementsByTagName("input");
for (key in inputFields) {
var myField = inputFields[key];
var myError = document.getElementById('errorMessage');
myField.onchange = function() {
var myPattern = this.pattern;
var myPlaceholder = this.placeholder;
var isValid = this.value.search(myPattern) >= 0;
if (!(isValid)) {
myError.innerHTML = "Input does not match expected pattern. " + myPlaceholder;
} else { //pattern not valid
myError.innerHTML = "";
} //pattern is valid
} // myField has changed
} // inputFields
<form id="createForm" name="theForm" method="post" action="createUser.php">
<legend><span class="icon"><img src="/registerUser/img/createIcon.png"></span> Create New User</legend>
<p><span id="requiredfields">* required field.</span>
</p>
<span id="formMessage" class="message"> </span>
<span id="errorMessage"> </span>
<input id="fname" type="text" name="fname" placeholder="Name *" pattern="[A-Za-z ]+" required>
<br>
<br>
<input id="email" type="email" name="email" placeholder="Email *" required>
<br>
<br>
<input id="username" type="text" name="username" placeholder="Username *" required>
<br>
<br>
<input id="password" type="password" name="password" placeholder="Password *" required>
<br>
<br>
<label for="roles">Roles:</label>
<select id="role" name="roles">
<option>Select Role</option>
<option value="empty"></option>
<option value="Reporter">Reporter</option>
<option value="Lover">Lover</option>
<option value="Other">Other</option>
</select>
<br>
<br>
<input id="create" type="submit" name="createUser" value="Create User">
</form>
When you specify an input element validation pattern as an html5 attribute like this:
pattern="[A-Za-z ]+"
...the browser checks that the whole input value matches the pattern. In other words, your pattern is treated like ^[A-Za-z ]+$ even though the ^ and $ are not explicitly in the pattern.
But in your JavaScript code when you use the pattern like this:
var myPattern = this.pattern; // get pattern from element
var isValid = this.value.search(myPattern) >= 0;
...the .search() method doesn't try to match the whole string, it returns the index of the first pattern match within the string. Which means that, e.g., in the case of your Name field your JS will consider it valid as long as at least one character matches the pattern, even if other characters don't.
The simplest way to work around this is to update your pattern:
pattern="^[A-Za-z ]+$"
Or you could update your JS something to be something like the following:
var isValid = !myPattern || this.value.search("^" + myPattern + "$") >= 0;
That is, put ^ and $ around the pattern to force JS to match the whole string against the pattern, but only do the test if a non-blank pattern was specified for the field (some of your fields don't have a pattern).
Issue
I am having a problem creating a custom validator for the Parsley.js plugin. What I'm trying to do is test a value vs a regex. Specifically, I'm trying to validate that a password value includes at least one uppercase and one lowercase letter. The validation code throws an error, but does not return true when the condition has been satisfied.
HTML
<form name="Form" id="signupform" method="post" action="#" data-parsley-validate data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden">
<label for="password1">New Password <span class="req">*</span></label>
<input name="password" id="password1" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspannewpassinput" data-parsley-required-message="Please enter your new password." data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" data-parsley-required/>
<span class="errorspannewpassinput"></span>
<label for="confirm_password1">Confirm Password <span class="req">* </span></label>
<input name="Password_2" id="password2" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspanconfirmnewpassinput" data-parsley-required-message="Please re-enter your new password." data-parsley-equalto="#password1" data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" data-parsley-required />
<span class="errorspanconfirmnewpassinput"></span>
<input type="submit" name="submitinfo" id="submitsignup" data-theme="b" style="width:100%;" alt="Sign Up Now" value="Submit Account Request" />
</form>
jQuery
$(function() {
// Set variables
var pmixedCase = 'Y';
var mixedCase = $('.mixedcase');
var passwordField = $('#password1, #password2');
var passwordFieldErrors = $('.errorspannewpassinput, .errorspanconfirmnewpassinput');
// Assemble list of visible password requirements
// Mixed Case
if (pmixedCase === 'Y') {
mixedCase.show();
} else {
mixedCase.hide();
}
// Custom Validators
window.Parsley.addValidator('mixedcase', {
requirementType: 'regexp',
validateString: function(value, requirement) {
return requirement.test(value);
},
messages: {
en: 'Your password must contain at least (1) lowercase and (1) uppercase letter.'
}
});
});
I've included a JSFiddle below.
Fiddle
The issue you're facing is that your JsFiddle is using Parsley 2.1.2 whereas the documentation is already updated to Parsley 2.2.0.
If you look at the Javascript console you'll see an error:
Uncaught TypeError: window.Parsley.addValidator is not a function
Which means that the version you're using is not yet updated (the previous versions used window.ParsleyValidator.addValidator). So, if you simply update Parsley.js to the correct version your code will work. See this fiddle.
However, there's a simpler way to accomplish what you need (that is, without a custom validator). You can use the built-in Pattern (data-parsley-pattern). For example:
<form name="Form" id="signupform" method="post" data-parsley-validate data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden">
<label for="password1">New Password <span class="req">*</span></label>
<input name="password" id="password1" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspannewpassinput" data-parsley-required-message="Please enter your new password." data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter." data-parsley-required />
<span class="errorspannewpassinput"></span>
<label for="confirm_password1">Confirm Password <span class="req">*</span></label>
<input name="Password_2" id="password2" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspanconfirmnewpassinput" data-parsley-required-message="Please re-enter your new password." data-parsley-equalto="#password1" data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" data-parsley-required data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter."/>
<span class="errorspanconfirmnewpassinput"></span>
<input type="submit" name="submitinfo" id="submitsignup" data-theme="b" style="width:100%;" alt="Sign Up Now" value="Submit Account Request" />
</form>
What I've changed:
Replaced data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" for data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" on both inputs.
As per Marc-André Lafortune's comment I removed the ^ at the start and the $ at the end, because the patterns are now anchored.
Added data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter." on both inputs.
JsFiddle available here.
I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form" action="" method="POST">
<input type=hidden name="" value="">
<input type=hidden name="" value="">
<p class="errmsg" id="name_errormsg"></p>
<input id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
<input id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
<input id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />
<textarea id="description" name="description" placeholder="How can we help you?"></textarea>
<input type="submit" name="submit" value="Send message">
</form>
$(document).ready(function() {
$overlay = $(".modal-overlay");
$modal = $(".modal-frame");
$modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
if($modal.hasClass('state-leave')) {
$modal.removeClass('state-leave');
}
});
$('.form-close-button').on('click', function(){
$overlay.removeClass('state-show');
$modal.removeClass('state-appear').addClass('state-leave');
});
$('#contactformbtn').on('click', function(){
$overlay.addClass('state-show');
$modal.removeClass('state-leave').addClass('state-appear');
});
var formHandle = document.forms[0];
formHandle.onsubmit = processForm;
function processForm(){
var emailInput = document.getElementById('email');
var emailValue = emailInput.value;
var phoneInput = document.getElementById('phone');
var phoneValue = phoneInput.value;
var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
var regexEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
nameErr = document.getElementById("name_errormsg");
nameErr.innerHTML = "Please enter your phone number or a valid email address.";
nameErr.style.color = "red";
return false;
}
}
});
If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
....
Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?