I am trying to validate my form phone field to prevent users from entering the same numbers in my javascript.
If the number provided by the user matches with the same numbers in my javascript, They will get a warning and the form would not submit.
However, I noticed that my code below shows the warning whether the numbers match or not.
I need corrections to know what I am doing wrong. Thanks.
Code below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" >
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<div class="validate"><span style="color: red;"><b>Please enter a valid phone!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
I believe this should work.
I move the changes for hiding and showing $('.validate') to the isphone function, and removed that done variable that wasn't doing anything useful (used if...else instead).
Also, don't use document.getElementById if you're already using JQuery.
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").hide();
} else {
$(".validate").show();
}
}
Related
I wrote a Javascript to validate my forms before submission.
The function of the Javascript is to prevent my form from submitting itself when a user provides a phone number that matches with the result in my Javascript but rather shows an error message that says "Phone number already used!"
My problem is that the validation works fine: Users get an alert that the phone number they provided has been used but my form still submits itself after showing the error message.
What am I not doing rightly?
Below is my code.
function check(form) /*function to check used phone number*/ {
/*the following code checkes whether the entered phone number is matching*/
if (form.phonenum.value == "0807575566464"
|| form.phonenum.value == "09057487463")
{
alert("Phone number used! provide a new one! \n") /*displays error message*/
} else if (form.phonenum.value.length<11 || form.phonenum.value.length>11) { alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
}
else {
return false;
}
}
<form action='' method='POST' enctype="multipart/form-data" id="formName">
<input type="text" id="phonenum" name="myinput">
<button href='/' type='submit' onclick="check(this.form)">Submit</button>
</form>
I think you need to add e.preventDefault() in order for it to stop reloading the page when you hit submit.
You need to bind a function to the onsubmit event and stop the event if the validaiton fails.
HTML:
<form action='' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
JavaScript:
function validateForm(event) {
if(validation fails...) {
event.preventDefault();
....
}
}
Documentation and examples for the preventDefault function:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Instead of using event.preventDefault() you could also just return false:
https://stackoverflow.com/a/65538474/9441244
In your case your JavaScript should look like this
HTML:
<form action='/test/' method='POST' enctype="multipart/form-data" id="formName" onsubmit="validateForm(event)">
<input type="text" id="phonenum" name="myinput">
<button href='/' type='submit'>Submit</button>
</form>
JavaScript:
function validateForm(event) {
if (this.phonenum.value == "0807575566464" || this.phonenum.value == "09057487463") {
event.preventDefault();
alert("Phone number used! provide a new one! \n");
} else if (this.phonenum.value.length != 11) {
this.preventDefault();
alert("Phone number should be 11 digits! \nAnd it should begin with; 080, 081, 070, 090, or 091.");
}
}
I'm trying to send messaging to the user that a field is required if they fail to input a value. I want the error to be displayed on the field itself, rather than a global error message at the top of the page.
If I do not enter any data into the form, it still allows submission. However, if I do not enter a username but I do enter mismatched passwords, the username field receives the validation message "Passwords do not match".
So, it appears to me, that for some reason my code to check if the input is null is not passing as True and so the function continues to my next condition.
Why isn't this function catching nulls?
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"
oninput="checkNull(this)" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password" oninput="checkNull(this)"
id="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmPassword" placeholder="Confirm Password" type="password"
oninput="check(this)" id="confirmPassword">
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
} else {
input.setCustomValidity('');
}
}
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
}
else {
input.setCustomValidity('');
}
</script>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I've tried some additional troubleshooting. I split my functions out, one to check for matching passwords, one to check for no input. I realized that by calling them in the same function I was comparing each to the password which is a problem.
As a sanity check, I then set to check for a specific string "foo". When passing in "foo", the error displays as expected, so I know at least the function is getting called.
I then tried to use "===" to compare the value rather than "==", but that didn't work either.
Code updated to reflect most recent changes.
When submit your form, it is not calling check() function. So, if you not touch any input, they will not be validated.
You can solve this by adding onsubmit="return validate()" to <form /> tag:
<form action="/register" method="post" onsubmit="return validate()">
Your validation function could be simple as:
var isValid = true;
function validate() {
isValid = true;
document.querySelectorAll('.form-control').forEach(check);
return isValid;
}
Notice the return keyword. When return value is false the submitting action will be cancelled. check() function should also mutate isValid variable:
function check(input) {
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
isValid = false;
}
else if (input.type == 'password' && input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
isValid = false;
}
else {
input.setCustomValidity('');
}
}
Also, you should only check if passwords are the same if you are validating a password input.
You can accomplish this by adding the extra condition to password validation: input.type == 'password'
You are calling your check method onchange, if you do not enter any text in the username field, your check method will not be called. So, the simple way to do this is to add required attribute on all your fields.
If you want to do it using JS, look at onsubmit method that gets triggered when the form's submit button is clicked.
Also, you should have three different methods for validating each of your fields. It will be hard to maintain and you will be cramping up one method with various checks.
You are using deprecated techniques here.. You should never attach a function to a form element in-line (within the html tag).
When it comes to checking password on keyup, you could use something like this with jquery:
var pwInputs = $(this).find('input[type=password]');
$('input[type=password]').keyup(() => {
pwarr = new Array();
pwInputs.each(function() {
pwarr.push($(this));
});
if (pwarr[0].val() != pwarr[1].val()) {
// Do work
}
if (pwarr[0].val() == null || pwarr[0].val() == "" & pwarr[1].val() == null || pwarr[1].val() == "") {
// Do Work
}
});
You could use jquery in a similar fashion to check values on submit.
$('#formid').on('submit', function() { // Do work })
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
I am a PHP developer and new to jQuery, I just wrote a few lines of code before and it was all from online sources. Anyways, I have these three inputs in html:
<input type="password" name="old-password" id="old-password">
<input type="password" name="new-password" id="new-password">
<input type="password" name="confirm-new-password" id="confirm-new-password">
<button type="submit" id="save" class="button button-primary">Save Changes</button>
I have a full page of settings and these three fields are for passwords, but I want to make them required only if the user enters any data into any of the inputs.
Example: A user types in old password input, all 3 inputs gets required real-time. Or a user types in confirm new password input, all 3 inputs gets required as well.
Thank you for the help.
Solution: The answers were all great and thank you everyone for the help. Another problem came up, is that if someone tries to backspace and remove the text on the form, it still stays required. I came up with a solution with the help of all the answers.
You have to add a .password class to all the wanted inputs, and then put this in script tags:
$('.password').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#old-password').removeAttr('required', '');
$('#new-password').removeAttr('required', '');
$('#confirm-new-password').removeAttr('required', '');
} else {
$('#old-password').attr('required', '');
$('#new-password').attr('required', '');
$('#confirm-new-password').attr('required', '');
}
});
Use .attr() on the oninput event.
i.e. something like this:
function makeRequired(){
$("#old-password").attr("required","");
$("#new-password").attr("required","");
$("#confirm-new-password").attr("required","");
}
And then bind it to oninput either in your HTML or in JS.
Using your condition
if the user enters any data into any of the inputs.
You could write this event
$("body").on("input", "#confirm-new-password,#new-password,#old-password", function()
{
$("#confirm-new-password").attr('required', 'required');
$("#new-password").attr('required', 'required');
$("#old-password").attr('required', 'required');
});
well, I extremly recommend to use a library like Jquery validate jqueryValidate
But, if you don't want to use, you can try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="password" name="old-password" id="old-password" class="passwordToCheck">
<input type="password" name="new-password" id="new-password" class="passwordToCheck">
<input type="password" name="confirm-new-password" id="confirm-new-password" class="passwordToCheck">
<button type="submit" id="save" class="button button-primary">Save Changes</button>
<script>
$(".passwordToCheck").change(function(){
passInput = $(this);
if(passInput.val().trim() != ""){
passInput.addClass("required");
} else {
passInput.removeClass("required");
}
});
$("#save").click(function(e){
e.preventDefault();
if($(".required").length >0){
alert("fill the fields!");
} else {
alert("OK");
$(this).submit();
}
});
</script>
adding a class to your password-type inputs, and working with required class ( you can change this easily by the required attr if you don't want to work with class required.
here is the fiddle:
jsfiddle
if ($("#old-password").val() != "" ||
$("#new-password").val() != "" ||
$("#confirm-new-password").val() != "") {
$("#old-password").attr("required");
$("#new-password").attr("required");
$("#confirm-new-password").attr("required");
}
So, I have a number textbox and I want to validate it using JavaScript. If the user has not input any number, it will prompt him/her to enter one. My codes below:
<input type="number" autofocus id="lol"/>
<input type="button" onClick="validate()" value="Input"/>
<script>
function validate() {
var numfield = document.getElementById("lol").value;
if ( numfield == "") {
document.write("Missing number!");
}
</script>
What is wrong?
You have missed a } at the end of the script. With that fixed, it works normally.
Try to use length property.
if ( numfield.length > 0) {
...
}