0

How to validate First Name and Last Name in one input textbox using javascript?i have one inputtext box.when i given first b=name then need to give one space and need to give lastname.when i given two spaces or more spaces after firstname need to validate lasname is required and remove all spaces and put one space between firstname and lastname.can anybody help me this.

Visualforce page:

<apex:inputtext value={!name} id="Name"/>
<apex:commandbutton onclick="validatenamevalue();"/>

javascript:

function validatenamevalue(){
   var name = document.getElementById('{!$Component.formId.Name}').value;
   if(name == '') {
     alert(firstname is required);
   } else if(!name.includes(' ')) {
     alert(last name is reqiured);
   }
}

when i given second space empty value is saving in lastname field.need to validate lastname is not empty.

3
  • 1
    If you have a wish to receive good answer then post your code Commented Jan 18, 2017 at 6:29
  • ok,i will updade my code.
    – user
    Commented Jan 18, 2017 at 6:31
  • 1
    First of all the apex:inputText needs to have value in double quotes i.e. <apex:inputtext value="{!name}" id="Name"/>
    – RCS
    Commented Jan 18, 2017 at 6:57

3 Answers 3

1

Try Below Code

VF Code

<apex:inputtext value="{!name}" id="Name"/>
<apex:commandbutton onclick="validatenamevalue();" reRender="someId"/>

Javascript

function validatenamevalue(){
   var name = document.getElementById('{!$Component.formId.Name}').value;
   if(name == '' || name == null) {
     alert('Please enter FirstName & LastName');
   } else if((name.indexOf(' ') > 0 && name.indexOf(' ') == (name.length)-1) || !(name.indexOf(' ') > 0)) {
     alert('Please Enter Last Name');
   }
}
0

You can refer the following link and modify your code accordingly - How to write Javascript validation for Visualforce page

0

You can use regex function for two consecutive spaces in visualForce page You can find the regex expression for javaScript in below link.

https://stackoverflow.com/questions/3758798/how-to-search-for-occurences-of-more-than-one-space-between-words-in-a-line

If you want to compare in visualForce page, use REGEX function of visualforce page. Below are the functions you can use in visualForce page(Search for regex function and program it accordingly).

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_functions.htm

Let me know if these were helpful

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .