Change default HTML input validation message - javascript

I want to override the error messages by e.g. Firefox for my HTML5 form with my own personal message. But doing this causes the input field I am applying it to to not allow the form to submit. It's as if you haven't filled in the input field and the error message keeps appearing instead.
HTML part
<label for="name">Name</label>
<input id="name" name="name" placeholder="Enter Your Name" required="" type="text">
Javascript (IIFE)
var change_text = function(){
var name = document.getElementById("name");
if (!name.checkValidity()) {
name.setCustomValidity("Please enter your full name");
name.reportValidity();
}
else {
name.setCustomValidity("");
}
}();
This does change the message to my bespoke message, but it won't allow the form to submit. Interestingly, if i change my message to an empty sting, it does work (but obviously the error message doesn't show.

You can use the input and invalid events to set your custom validation message.
let name = document.getElementById("name");
name.addEventListener("input", function(e){
name.setCustomValidity('');//remove message when new text is input
});
name.addEventListener("invalid", function(e){
name.setCustomValidity('Please enter your full name');//custom validation message for invalid text
});
<form>
<label for="name">Name</label>
<input id="name" name="name" placeholder="Enter Your Name" type="text" required autocomplete="off">
</form>

Related

where the error messages will be inserted when the errors that they represent occur

I'm having an issue figuring out how to write the following code:
the problem is that I'm using an empty <div> with the id error-display. This <div> is where the error messages will be inserted when the errors that they represent occur. I want to make all fields validated when the user clicks off of them to the next field. If there’s an error, an error message should be displayed. Likewise, error messages should be removed when the user fixes the problem. yet I'm not sure how to do it! here is what I got so far:
<div id="error-display">
</div>
<form id="project-form">
<br>E-mail:<span class="error">* </span>
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
<br>Password:<span class="error">* </span>
<input type="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password" required>
<br>Confirm Password:<span class="error">* </span>
<input type="password" placeholder="Repeat Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password-confirmation" required>
After inserting the emipty "div id="error-display">" what can I do?
lets say the error message is: Invalid email address.
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
I tried "required" in the input elements and it's working for my inputs, however, I think my professor is looking for a different solution.
I suggest you to add change event listener for every input field and to validate each of them and if some are invalid you should set innerText property of the 'error-display' div to error message text
Here's a quick and simple solution for you
in all of your input fields, put onchange="validateField(fieldID, fieldname)" like this
<input type="email" name="email" id="email" onchange="validateField('email', 'Email')" placeholder="Example#example.com" required>
then paste this script below your form (or you can have this in a separate js file)
<script>
function validateField(fieldID, fieldname) {
var inpObj = document.getElementById(fieldID);
if (!inpObj.checkValidity()) {
document.getElementById("error-display").innerHTML = "Invalid " + fieldname + ":" + inpObj.validationMessage;
} else {
//this will clear your error if the input is already correct
document.getElementById("error-display").innerHTML = "";
}
}
</script>

Issues with form validation with Javascript

I am having some issues validating my input fields with using Javascript.
I'm trying to make it so when u put for example your name in the input field, it should appear as a green border (which kinda works already) and when nothing is filled in, it should return as a red border and not be allowed to send the form. (it doesn't actually need to send it, no php).
It also should rewrite the placeholder (in this case) with the name you entered.
It should validate all the fields before pressing the button. (so they should all turn out red or green, currently does it only for the first input field)
Also, could you help me out with validating the email field on a legit adress (so validating the # and a .).
function nietLeeg() {
var tekstveld = document.getElementById('checkField');
if (tekstveld.value != "") {
document.getElementById("checkField").style.borderColor = "green";
document.getElementById("checkField").value = "";
} else {
document.getElementById("checkField").style.borderColor = "red";
}
}
<form method="POST" action="#">
<input type="text" id="checkField" value="your name">
<input type="email" id="checkField" value="your email">
<textarea rows="4" cols="50" placeholder="Write your message here"></textarea>
<input type="button" class="submitbtn" value="Send" onclick="nietLeeg();">
</form>

How to validate for either form fields with vanilla JavaScript

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?

How to validate form fields on its default values using serializeArray().?

Have a basic registration form, trying to validate it.
I am using form serializeArray() method and loop trough the form and find if the values are null.
HTML CODE
<form name="reg" id="regform">
<fieldset>
<label for="firstname">First Name</label>
<input type="text" name="firstname" value="First Name"/>
</fieldset>
<fieldset>
<label for="lastname">Last name</label>
<input type="text" name="lastname" value="Last Name"/>
</fieldset>
<fieldset>
<label for="date">Age</label>
<input type="text" name="age"/>
</fieldset>
</form>
JQUERY Code
var formElements = $("#regform").serializeArray();
$(formElements).each(function(x)
{
if(formElements[x]["value"] == "")
{
$("[name='" + formElements[x]['name'] +"']").addClass('error');
}
});
From the above code i am able to add the class ".error" when the value is null.
Now i want the code to check the text fields values are not the default values like in my case the default values are "First Name" "Last Name"..
So i want to check even for the default values and add error class to respective element and even focus back the cursor on the first null value text field
Thanks in advance
I highly suggest using http://docs.jquery.com/Plugins/Validation. You can test for various things, such as blank values, and even extend it to detect default values.
For example:
$.validator.addMethod("name", function(value) {
return value != "First Name";
}, 'Please enter your first name.');
Alternatively you can just test against a default value with jQuery's data() function:
Working Demo: http://jsfiddle.net/WpQ2n/2/
var input = $(".name"),
defaultval = input.data("default", input.val());
// Can't submit forms in jsfid, so i just used a click event.
// Change to .submit()
$("input[type='submit']").on("click",function(e){
if(input.val()== input.data("default")){
input.addClass("error");
}
else{
// Yay it validated...
input.removeClass("error");
}
e.preventDefault();
});

Conflicting Javascript preventing form validation

im trying to validate a form before its submitted to the database but something seems to be conflicting with it and its just sending anyway without any values
heres my form:
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<span style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px;">Ally McCoist will be sacked on</span>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/submit-button-small.png" name="submit" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres my validate javascript:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(e){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
i also have this javascript on the page fore my jquery UI datepicker which i think might be causing the problem
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
fingers crossed one of you can see something that might fix this problem
It is possible that the form was filled out by a person with JavaScript disabled or that a person or machine simply invoked an HTTP POST, with whatever values they saw fit. For this reason, it is necessary to perform validation on the server-side (i.e. in send.php), not just on the client-side (in the JavaScript file). JavaScript validation is really just a UI optimization that allows a user to be immediately told that something is wrong without requiring a round-trip communication to the server. From a user-interface perspective, JavaScript validation is important, but from a security perspective it is useless.

Categories