I have an input field for which I need to make sure the input is only and only characters from the alphabet, with no:
numbers
special characters
number + alphabet combinations
I want to do this using if else statement only. So far the code is:
HTML:
<form id="myform" onsubmit="return check();" >
<input class="input" type="text" name="firstname">
And JavaScript is:
function check() {
var x = document.forms["myform"]["firstname"].value;
if (x == null || x == ""){
myform.action="firstnameerror.html";}
if (isNaN(x)) {
myform.action="lastname.html";
} else {
myform.action="firstnameerror1.html"
}
}
You can check it using regular expressions (RegExp), specifically with the .test() function:
if(/[^a-zA-Z]/.test(x))
// code to throw error
This will run the code to throw an error if any non-alphabetic character is contained in x.
Related
I'm trying to make a validation for my form with JavaScript. This is what I have done so far, and it works, but in the input "klassekode" needs to start with two letters and then one number.
My html code
<form class="form1" method="POST" id="registrerFagSkjema" action="registrerklasse.php" name="registrerFagSkjema" onSubmit="return validerRegistrerFag()">
Registrer klasse <br> <br>
Klassekode <br>
<input value="" type="text" name="fagkode" id="fagkode" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"
onChange="endreTilStoreBokstaver(this)"/ /><br>
Klassenavn <br>
<input value="" type="text" name="klassenavn" id="klassenavn" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()" />
<input value="Registrer Klasse" type="submit" name="submit" id="submit" >
<input type="reset" value="Nullstill" id="reset" name="reset" onClick="fjernMelding()">
</form>
<div id="melding"></div>
My JavaScript code
function validate()
{
var klassekode = document.getElementById("klassekode");
var klassenavn = document.getElementById("klassenavn");
var feilmelding="";
//var firstTwoLetters = document.getElementById("klassekode").substring(0,2);
if(klassekode.value.trim()=="")
{
//alert("blank");
feilmelding="Fyll ut Klassekode";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassekode.style.border = "solid 1px red";
return false;
}
else if ( klassekode.value.trim().length!=3)
{
//alert("klassekode for lang");
feilmelding="Klassekode må kun være 3 bokstaver";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else if (klassenavn.value.trim()=="" )
{
//alert("blank");
feilmelding="Fyll ut Klassenavn";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else { return true;}
}
You got the hang of substring, and you can use that the newer method isNaN (Not a Number) and divide your third character with 1. If it's a letter, isNaN will return "true" and if it's a number, it will return "false".
I would, however, recommend you to learn regular expressions, as it will benefit you tremendously in the future.
You basically create a pattern and then test a string against that pattern. If you find a match, then it's correct. I made a snippet below to demonstrate:
function validateInput() {
let inputElement = document.getElementById("namn");
let divElement = document.getElementById("comment");
var message = "not true";
let inputValue = inputElement.value.trim();
let pattern = new RegExp(/^[a-zøæ]{2}\d{1}/, "i");
if (isValid(inputValue, pattern)) {
message = "true"
}
divElement.innerHTML = message;
}
function isValid(str, pattern) {
return str.match(pattern);
}
<input id="namn" type="input" value="">
<input type="button" onclick="validateInput()" value="Validate" />
<div id="comment"></div>
This row needs explanation:
let pattern = new RegExp(/^\d{1}[a-zøæ]{2}/, "i");
The regular expression contains expressions that can be stringed together:
^: start at the beginning of the string.
[a-zøæ]{2}: 2 characters must be between a-z or contain ø or æ.
\d{1}: next following 1 character must be a digit.
The flag "i" makes the a-z case insensitive. Another way would be to don't add a flag, and instead write [a-zA-ZøØæÆ]
Regex to the rescue. You can add another else if statement as per the following:
else if (klassekode.value.trim().length !== 3) {
// after checking whether the string length is 3 characters...
} else if (!klassekode.value.trim().match(/^[a-z]{2}\d/i)) {
// apply validation warning styles
return false;
}
An explanation of the Regex:
^ - asserts position at the start of the string
[a-z] - matches an alphabetic character
{2} - matches exactly twice
\d - matches a digit (0-9) once
i - case insensitive match
I am not checking the string length again because your previous condition accounts for it.
Ensure to trim() the value before using it (e.g. before sending it to the backend for processing, etc.), because otherwise the leading/trailing spaces will be retained.
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'm a new learner of javascript.
So I have this html textbox.
<form method="get" id="form" action="number.php">
<p><input type="text" id="number" name="number" value="0,0" size="4"/></p>
</form>
And with javascript (not jquery), a regex expression and without changing the html code, I only want to allow an input of positive numbers or a pos. number followed by a comma followed by only one number after comma.
E.g. 5 or 23 or 141 or 0
E.g. 15,9 or 0,0 or 356,4 or 77,7
This is how my javascript function looks like but I am not sure how to call the function for the input of this textfield "number". And not sure if my regex is correct.
number.onkeypress = function validate(s) {
var rgx = /^\d+(,\d{1,1})?$/ ;
if(rgx.test(s)) {
return true;
}
else {
return false;
}
}
So my 2 questions are:
How can I check with a regex-function the input for the textbox, so only numbers and one comma is allowed?
Is my regex expression correct?
You try this
<p><input type="text" id="number" name="number" value="0,0" onblur="javascript:validate()" size="4"/></p>
<script>
function validate() {
var numberVar = document.getElementById("number");
var rgx = /^\d+(,\d{1,1})?$/;
if(!rgx.test(numberVar.value)) {
numberVar.value = "";
numberVar.focus();
}
}
</script>
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/
I have a javascript function written to validate a field on my form. This function is supposed to make sure the field is not empty, does not exceed the limit of 35 characters and only contains alphabetic characters and a hyphen(-). I had code to make sure the field is not empty and that it does not exceed 35 characters which worked fine but i added code to validate the field to the usable characters and i tested it out by leaving the field empty to make sure that still worked but when i hit the submit button the function didn't seem to validate at all, didn't give me an alert and just submitted. Here is my code:
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z\-\]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
}
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone show me how to fix my code?
Your regular expression is broken. You've escaped the closing square bracket around the character set. Try this:
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
Also, there's a lot of weird clutter in there that's annoying but not fatal: How many times do you really need to call getElementById('family') in that method? Once.
if (stringf=="")
{
alert("Family name must be filled out");
return false;
}
else if (stringf.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
UPDATED:
Sorry, the problem is with your regex, i missed that, change to this its fully working:
var ck_password = /^[A-Za-z0-9-]/;
if(!ck_password.test(stringf))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
}
Console in chrome, go to the OPTIONS in the right top coner, select TOOLS, then DEVELOPER TOOLS.
Try to rename submit button, rid of id and name "submit" (rename to "doSubmit" or smth), it can cause problems and conflict with event "submit" of form.