jQuery Click Function, input value length and pattern - javascript

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.

Related

How To Validate Form Field Using Javascript

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();
}
}

The form does not work correctly when sent

I wrote the code for a form validation.
Should work like this:
It checks (allLetter (uName)) and if it's true, then validate the next input.
If any validation is false then it should return false.
My problem is that if both validations are true, then everything is exactly false and the form is not sent.
If I set true in formValidation (), if at least one check false, the form should not be sent.
<form name='registration' method="POST" onSubmit="return formValidation();">
<label for="userName">Name:</label>
<input type="text" name="userName" size="20" />
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" size="20" />
<input type="submit" name="submit" value="Submit" />
</form>
function formValidation() {
var uName = document.registration.userName;
var uPhone = document.registration.userPhone;
if(allLetter(uName)) {
if(phone(uPhone)) {}
}
return false;
}
function phone(uPhone){
var digts = /^[0-9]+$/;
if(uPhone.value.match(digts)){
return true;
} else {
alert('Phone must have only digits');
uPhone.focus();
return false;
}
}
function allLetter(uName) {
var letters = /^[A-Za-z]+$/;
if(uName.value.match(letters)) {
return true;
}else{
alert('Username must have alphabet characters only');
uName.focus();
return false;
}
}
First, you are using a 20+ year old way to gain references to your elements (document.form.formElementNameAttributeValue) and, while this still works for legacy reasons, it doesn't follow the standard Document Object Model (DOM) API.
Next, you've broken up your validation tests into different methods (and that's certainly not a bad idea for reusability), but in this case is is adding a ton of code that you just don't need. I've always found it's best to start simple and get the code working, then refactor it.
You're also not using the <label> elements correctly.
One other point, your form is set to send its data via a POST request. POST should only be used when you are changing the state of the server (i.e. you are adding, editing or deleting some data on the server). If that's what your form does, you'r fine. But, if not, you should be using a GET request.
Lastly, you are also using a 20+ year old technique for setting up event handlers using inline HTML event attributes (onsubmit), which should no longer be used for many reasons. Additionally, when using this technique, you have to use return false from your validation function and then return in front of the validation function name in the attribute to cancel the event instead of just using event.preventDefault().
So, here is a modern, standards-based approach to your validation:
// Get references to the elements you'll be working with using the DOM API
var frm = document.querySelector("form[name='registration']");
var user = document.getElementById("userName");
var phone = document.getElementById("userPhone");
// Set up event handlers in JavaScript, not with HTML attributes
frm.addEventListener("submit", formValidation);
// Validation function will automatically be passed a reference
// the to event it's associated with (the submit event in this case).
// As you can see, the function is prepared to recieve that argument
// with the "event" parameter.
function formValidation(event) {
var letters = /^[A-Za-z]+$/;
var digts = /^[0-9]+$/;
// This will not only be used to show any errors, but we'll also use
// it to know if there were any errors.
var errorMessage = "";
// Validate the user name
if(user.value.match(letters)) {
// We've already validated the user name, so all we need to
// know now is if the phone is NOT valid. By prepending a !
// to the test, we reverse the logic and are now testing to
// see if the phone does NOT match the regular expression
if(!phone.value.match(digts)) {
// Invalid phone number
errorMessage = "Phone must have only digits";
phone.focus();
}
} else {
// Invalid user name
errorMessage = "Username must have alphabet characters only";
user.focus();
}
// If there is an error message, we've got a validation issue
if(errorMessage !== ""){
alert(errorMessage);
event.preventDefault(); // Stop the form submission
}
}
<!-- 20 is the default size for input elements, but if you do
want to change it do it via CSS, not HTML attributes -->
<form name='registration' method="POST">
<!-- The for attribute of a label must be equal to the id
attribute of some other element, not the name attribute -->
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userPhone">Phone:</label>
<input type="text" name="userPhone" id="userPhone">
<input type="submit" name="submit" value="Submit">
</form>

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

Only allow HTML field to start with certain words

Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/

JavaScript empty field validation does not work

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) {
...
}

Categories