1

I am trying to validate my model data which is a text box for string entry but when I try to test with int entry, I get no error and it is saved to the database ...

How can I prevent this?

Model class:

[Required]
public string DeptName { get; set; }

Action method:

public ActionResult Update(Dept model)
{
        if (!ModelState.IsValid)
        {
            return View();
        }

        db.Entry(model).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
}

View:

@model Dept

@using (Html.BeginForm())
{
    @Html.HiddenFor(a => a.DeptId);
    @Html.TextBoxFor(a => a.DeptName);
    @Html.ValidationMessageFor(a => a.DeptName);
    <input value="Update" type="submit" class="btn btn-info" />
}

2 Answers 2

1

If you use only [Required] attribute then its check the value empty or not, It's no check the value type int or string.

If you want to allow the only alphabet characters in a textbox. you can use the regular expression

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string DeptName {get; set;}
Sign up to request clarification or add additional context in comments.

Comments

0
[RegularExpression("[a-zA-Z]*", ErrorMessage = "Cannot be a number")]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.