Cybercop
Cybercop

Reputation: 8694

MVC Client side validation: At least one of two textboxes must be filled

I need to create a validator where at least either FirstName or LastName must be filled.

public class Person
{

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

I want user to provide at least, either first name or last name. Providing both shouldn't be a prob. This is currently what I have at view

@Html.ValidationSummary(true)
@using(Html.BeginForm("AddPerson","Person",FormMethod.Post))
{

    <div class="label">First Name</div>
    <div class="input-block-level">@Html.TextBoxFor(m=>m.FirstName)</div>
    <br/>
    <div class="label">Last Name</div>
    <div class="input-block-level">@Html.TextBoxFor(m=>m.LastName)</div>

    <button type="submit" class="btn-primary">Submit</button>
}

What should I do to validate the form on the client side so that error is thrown when at least one textbox is not filled??

Upvotes: 1

Views: 1642

Answers (1)

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

try this

<input type="submit" value="Submit" class="btn-primary" onclick="javascript: return checkform()" >

function checkform()
{
var fname= $('#FirstName').val();
var lname= $('#LastName').val();
if(fname=="" && lname=="")
  {
    alert("Enter either first name or last name") ;
    return false;
  }
}

Upvotes: 1

Related Questions