1

So I have a object that is passed back.The object is a bunch of survey questions, with option to enter response. This object has a variable called "Mandatory" meaning that this questions is mandatory.

So we can display the questions and also pass back answers ("o.Answertext"). But I am struggling to set up the mandatory field validation.

<div ng-if="o.QuestionType == 'Text'">
    <textarea class="form-control" ng-model="o.AnswerText"
            name="{{o.SurveyQuestionId}}" rows="5" id="comment"></textarea>
    <br />
    <div ng-if="o.Mandatory == true">
        <span style="color:red" ng-if="form.$submitted || form.o.SurveyQuestionId.$touched"
                ng-show="form.o.SurveyQuestionId.$error.required">
            Required
        </span>
    </div>
</div>

I can see that ng-if="o.Mandatory == true becomes activated. But my span ng-if never becomes activated.

3
  • Log the value of $scope.o.QuestionType to debug. Commented Feb 22, 2016 at 0:53
  • You'll need to use square bracket notation due to the dynamic element name, ie form[o.SurveyQuestionId].$touched, form[o.SurveyQuestionId].$error.required, etc Commented Feb 22, 2016 at 0:55
  • The issue is making the ng-if in the span active. I need that to confirm validation. Commented Feb 22, 2016 at 0:56

1 Answer 1

2

DEMO Use ng-required in your <textarea>

<form name='mainForm'>
 <div ng-if="o.QuestionType == 'Text'">
    <textarea class="form-control" ng-required='o.Mandatory'
           name='{{o.SurveyQuestionId}}' ng-model="o.AnswerText" rows="5" id="comment"></textarea>
    <br />
    <div style='color: red' ng-if="mainForm[o.SurveyQuestionId].$touched &&  mainForm[o.SurveyQuestionId].$error.required">
            Required
        </span>
    </div>
  </div>
</form>

here's the docs

Sign up to request clarification or add additional context in comments.

4 Comments

See my comment above about the form element name. It's not literally SurveyQuestionId
@Phil I edited my answer, I think it's correct now :)
got this working by instead of adding required='' instead of 'ng-required' thanks so much for your help!
@test, no problem. Hmmm, Based on what you've done with required='' have you tried setting o.Mandatory = false and still got the correct result?

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.